<?php
//In this file we will store most of the PHP functions we 'll use

//Function 'connect ()' let us connect to our database. We have to include the config.php file before using this.
function connect () {
global $db;

if (!is_array($db)) {
	return false;
}

if (!mysql_connect($db['host'],$db['user'],$db['pass'])) {
	return false;
}

if (!mysql_select_db($db['name'])) {
	return false;
}

return true;
}

//The function safe_query () lets us execute MySQL queries in a safe way.
function safe_query ($query, $data) {
global $uid, $alerts;
$data = prepare_mysql_data($data);
$parts = explode( '?', $query );
$query = '';
foreach ( $data as $value ) {
	$query .= array_shift( $parts );
	$query .= $value;
}
$query .= array_shift( $parts );
return mysql_query($query) or die( mysql_error() );
}

//The function easyfetch () lets us fetch easily data from a MySQL table
function easyfetch ( $fields, $table, $options = NULL ) {
global $uid, $alerts;
if ( !is_array( $fields ) ) {
	$fields = explode( ',', $fields );
}
$data = prepare_mysql_data ( $fields );
$data = implode( ' , ', $data );
$query = "SELECT $data FROM $table $options;";
$result = mysql_query( $query );
if ( !$result ) {
	$alerts[] = 'An error occured while fetching your data.';
	return false;
}
$rows = array(  );
while ( $row = mysql_fetch_array( $result ) ) {
	$rows[] = $row;
}
return $rows;
}

//The function prepare_mysql_data () prepares data so as to be used by safe_query ()
function prepare_mysql_data ($data) {
$i=0;
while ($data[$i]) {
	$data[$i]=addslashes($data[$i]);
	$i++;
}
return $data;
}

//Function value_exists () let us check if that specific field value alreasy exists in the database or not
function value_exists ($val, $field='uname', $table='users') {
$fetched_val=easyfetch ( $field , $table , "WHERE uname='$val'");
if (count($fetched_val)===0) {
	return false;
}
return true;
}

//Function hash_pwd () hashes the password
function hash_pwd ($pass) {
global $salt;
return hash('sha256', $pass.$salt);
}

//Function register_user () just registers a user to the system
function register_user ($uname, $pass, $email) {
$pass=hash_pwd($pass);
$date=date('Y-m-d');
$data=prepare_mysql_data (array($uname, $pass, $email, $date));
$query="INSERT INTO users SET uname='?', pass='?', email='?', date='?';";
if (safe_query ($query, $data)) {
	return mysql_insert_id ();
}
return false;
}

//Function check_credentials () checks if the given username/email matches the given password.
function check_credentials ($uname, $pass) {
global $pattern;
$val=$uname;
$p=$pass;
$pass=hash_pwd($pass);
if (preg_match($pattern['uname'], $val)!=1) {
	if (preg_match($pattern['email'], $val)!=1) {
		$field='none';
	}else{
		$field='email';
	}
}else{
	$field='uname';
}

if ($field=='none') {
	$arr=array("successful"=>"false", "message"=>"Please enter valid information.");
}else{
	$res=easyfetch ("uid, uname", "users", "WHERE $field='$val' AND pass='$pass'");
	if (count($res)===0) {
		$arr=array("successful"=>"false", "message"=>"Incorrect login information.");
	}else if (count($res)===1) {
		$arr=array("successful"=>"true", "uid"=>$res[0]['uid'], "uname"=>$res[0]['uname']);
	}else{
		$arr=array("successful"=>"false", "message"=>"Unknown error.");
	}
}

return $arr;
}

//Function cookie_auth () generates a cookie auth string based on the given uname and pass
function cookie_auth ($uname, $pass) {
global $salt;
return md5(hash('sha256', $uname).$salt.sha1($pass));
}

//Function login_user () creates the required cookies for the user to stay signed in
function login_user ($uid, $uname, $pass, $stay=false) {
global $salt;
return ( setcookie('uid', $uid, 0, '/') && setcookie('auth', cookie_auth ($uname, $pass), 0, '/') );
}

//Function logout_user () destroys the "log in cookies"
function logout_user () {
return (setcookie('uid', '', mktime () -3600, '/') && setcookie('auth', '', mktime () -3600, '/'));
}
?>